/******************************************************************************* 
 * Copyright (C) 2012-2015 Microfountain Technology, Inc. All Rights Reserved. 
 * 
 * Unauthorized copying of this file, via any medium is strictly prohibited.   
 * Proprietary and confidential
 * 
 * Last Modified: 2015-9-19 14:49:36
 ******************************************************************************/
package cn.cmcc.online.smsapi.util;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.os.Process;
import cn.cmcc.online.smsapi.sdk.Iservice.OnlineUpdateCycleConfigInterface;
import cn.cmcc.online.smsapi.sdk.action.AbsSdkDoAction;
import cn.cmcc.online.smsapi.sdk.constant.Constant;
import cn.cmcc.online.smsapi.sdk.db.DBManager;
import cn.cmcc.online.smsapi.sdk.db.MenuInfoManager;
import cn.cmcc.online.smsapi.sdk.db.ParseItemManager;
import cn.cmcc.online.smsapi.sdk.db.entity.JarSubInfoManager;
import cn.cmcc.online.smsapi.sdk.db.entity.MatchCacheManager;
import cn.cmcc.online.smsapi.sdk.db.entity.MenuInfo;
import cn.cmcc.online.smsapi.sdk.db.entity.SysParamEntityManager;
import cn.cmcc.online.smsapi.sdk.db.entity.pubinfo.PubInfoManager;
import cn.cmcc.online.smsapi.sdk.dex.DexUtil;
import cn.cmcc.online.smsapi.sdk.iccid.IccidLocationUtil;
import cn.cmcc.online.smsapi.sdk.log.LogManager;
import cn.cmcc.online.smsapi.sdk.net.BaseHttpRunnable;
import cn.cmcc.online.smsapi.sdk.net.NetUtil;
import cn.cmcc.online.smsapi.sdk.net.XyHttpRunnable;
import cn.cmcc.online.smsapi.sdk.net.util.SigntureUtil;
import cn.cmcc.online.smsapi.sdk.queue.EmergencyQueue;
import cn.cmcc.online.smsapi.sdk.queue.SdkTaskQueue;
import cn.cmcc.online.smsapi.sdk.queue.TaskInfo;
import cn.cmcc.online.smsapi.sdk.service.baseparse.BaseParseService;
import cn.cmcc.online.smsapi.sdk.service.pubInfo.PubInfoNetService;
import cn.cmcc.online.smsapi.sdk.service.pubInfo.PubInfoService;
import cn.cmcc.online.smsapi.sdk.service.pubInfo.PublicInfoCacheManager;
import cn.cmcc.online.smsapi.sdk.service.travel.TravelService;
import cn.cmcc.online.smsapi.sdk.smsmessage.BusinessSmsMessage;
import cn.cmcc.online.smsapi.sdk.threadpool.SmartSmsThreadPoolManager;
import cn.cmcc.online.smsapi.sdk.ui.popu.util.ViewUtil;
import cn.cmcc.online.smsapi.sdk.util.ConversationManager;
import cn.cmcc.online.smsapi.sdk.util.DateUtils;
import cn.cmcc.online.smsapi.sdk.util.DuoquUtils;
import cn.cmcc.online.smsapi.sdk.util.FileUtils;
import cn.cmcc.online.smsapi.sdk.util.InitUtil;
import cn.cmcc.online.smsapi.sdk.util.JarSubCheckQueue;
import cn.cmcc.online.smsapi.sdk.util.KeyManager;
import cn.cmcc.online.smsapi.sdk.util.LogSdkDoAction;
import cn.cmcc.online.smsapi.sdk.util.PopupUtil;
import cn.cmcc.online.smsapi.sdk.util.RecordFunctionUtil;
import cn.cmcc.online.smsapi.sdk.util.SdkCache;
import cn.cmcc.online.smsapi.sdk.util.StringUtils;
import cn.cmcc.online.smsapi.sdk.util.XyUtil;

public class ParseManager {

    // 版本号日期格式
    private static final String verDateFormat = "yyyyMMdd";
    
   
    public static final String UPDATE_ICCID_INFO_CACHE_ACTION = "cn.com.xy.sms.iccidinfo.action";

    private static boolean mUseNewDes = false;

    public static boolean ismUseNewDes() {
        return mUseNewDes;
    }

    public static void setmUseNewDes(boolean mUseNewDes) {
        ParseManager.mUseNewDes = mUseNewDes;
    }

    private static BroadcastReceiver mBroadcastReceiver = null; /*
                                                                 * new
                                                                 * BroadcastReceiver
                                                                 * () {
                                                                 * 
                                                                 * @Override
                                                                 * public void
                                                                 * onReceive
                                                                 * (Context
                                                                 * context,
                                                                 * Intent
                                                                 * intent) {
                                                                 * String action
                                                                 * =
                                                                 * intent.getAction
                                                                 * (); if (
                                                                 * UPDATE_ICCID_INFO_CACHE_ACTION
                                                                 * .
                                                                 * equals(action
                                                                 * )) { String
                                                                 * iccid =
                                                                 * intent
                                                                 * .getStringExtra
                                                                 * ("iccid"); if
                                                                 * (StringUtils.
                                                                 * isNull
                                                                 * (iccid)) {
                                                                 * return; }
                                                                 * IccidInfo
                                                                 * iccidData =
                                                                 * IccidInfoManager
                                                                 * .
                                                                 * queryIccidInfo
                                                                 * (iccid,
                                                                 * null); if
                                                                 * (iccidData !=
                                                                 * null) { //
                                                                 * 添加或更新数据缓存
                                                                 * IccidLocationUtil
                                                                 * .
                                                                 * putIccidAreaCodeToCache
                                                                 * (iccid,
                                                                 * iccidData
                                                                 * .areaCode,
                                                                 * iccidData
                                                                 * .operator,
                                                                 * iccidData
                                                                 * .userAreacode
                                                                 * , iccidData.
                                                                 * userOperator
                                                                 * ); } } } };
                                                                 */


    /**
     * 设置sdk 动作实例
     * 
     * @param action
     */
    public static void setSdkDoAction(AbsSdkDoAction action) {
        DuoquUtils.sdkAction = action;
    }
 

    /**
     * 执行动作
     * 
     * @param ac
     *            活动上下文
     * @param actionData
     *            动作指令
     * @param extend
     *            扩展参数
     * @return
     * @throws Exception
     */
    public static boolean doAction(Activity ac, String actionData, Map<String, String> extend) throws Exception {
        return DuoquUtils.doAction(ac, actionData, extend);
    }
    
    /*SDK-731 zhaojiangwei 20170310 start */
    public static boolean parseUtilMainJarIsReady(){      
        if (FileUtils.isFileExists(Constant.getPARSE_PATH(), "parseUtilMain", "jar") && SigntureUtil.getSignResult(Constant.getJarPath())) {
            return true;
        }
        return false;
    }
    /*SDK-731 zhaojiangwei 20170310 end */

    public static void initSdk(final Context context, final String channel, final String simIccid, final boolean preLoadEnable, final boolean smsLocateEnable, final Map<String, String> extend) throws Exception {
        if (context == null) {
            throw new Exception("context is null,please check.");
        }
        
        /*SDK-687 zhaojiangwei 20161128 start */
        if (extend==null || !extend.containsKey(Constant.RSAPRVKEY)) {
        	throw new Exception("rsa key is null,please check.");
		}
        /*SDK-687 zhaojiangwei 20161128 end */
        
        Constant.initContext(context);
        /*SDK-732 songzhirong 20170314 start*/
        KeyManager.channel = channel;
        /*SDK-732 songzhirong 20170314 end*/
        
        /* SDK-661zhaojiangwei 20161104 start */
        /* SDK-584 zhaojiangwei 20160905 start */
        //注册全局异常处理Hanlder.
//		CrashHandler crashHandler = CrashHandler.getInstance();
//		crashHandler.init(context);
		/* SDK-584 zhaojiangwei 20160905 end */
        /* SDK-661zhaojiangwei 20161104 end */	
        // 注册更新iccid数据广播
        BaseParseService.registerReceiver(context,extend);

        int pid = android.os.Process.myPid();
        String processName = AbsSdkDoAction.getCurProcessName(pid, context);
        /* SDK-537 hewengao 20160714 start */
        boolean initMainProcess = true;
        try {
            if (extend != null
                    && Boolean.FALSE.toString().equalsIgnoreCase((String) extend.get(Constant.INIT_MAIN_PROCCESS))) {
                initMainProcess = false;
            }
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "init SDK ", e);
        }
        if (initMainProcess && !context.getPackageName().equals(processName)) {
            // 进程名不是应用包名，说明不是主进程。
            LogManager.d("xiaoyuan", "processName is not " , context.getPackageName());
            return;
        }
        /*SDK-645  hewengao 20161019 start*/
        SigntureUtil.loadJarSignData();
        /*SDK-645  hewengao 20161019 end*/
        /* SDK-537 hewengao 20160714 end */
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    Context applicationContext = context.getApplicationContext();
                    if (applicationContext == null) {
                        applicationContext = context;
                    }
                    SysParamEntityManager.initParams(applicationContext, channel, simIccid, preLoadEnable, smsLocateEnable, extend);
                    SigntureUtil.checkChannel(channel,XyUtil.getMapValue(extend, Constant.CONFIG_APPKEY, ""));
                    SdkTaskQueue.startTaskQueue();

                    // 初始化内嵌数据
                    InitUtil.initInerData();
                    /*SDK-673 hewengao 20161114 start */
                    DexUtil.beforeInitBigJar();
                    /*SDK-673 hewengao 20161114 end */                 

                    SdkTaskQueue.addTask(new TaskInfo(2));
                    SdkTaskQueue.addTask(new TaskInfo(7));
//                    SdkTaskQueue.addTask(new TaskInfo(8));

                    IccidLocationUtil.changeIccidAreaCode(true);
                    /*SDK-431 songzhirong 20160530 start*/
                    BaseHttpRunnable.getDeviceId(false);
                    /*SDK-431 songzhirong 20160530 end*/
                  
                } catch (Throwable e) {
                    LogManager.e(Constant.TAG, "ParseManager.initSdk ", e);
                }
            }
        };
        if (extend != null && extend.containsKey("SYNCHRONIZED")) {
            run.run();
        } else {
            NetUtil.executeRunnable(run);
        }

    }
  
    // 注销广播接收者
    public static void unRegisterReceiver(Context context) {
        BaseParseService.unRegisterReceiver(context);
    }

    static Map<String, Object> parseMsg(Context ctx, String phoneNumber, String smsCenterNum, String smsContent, long smsTime, Map<String, String> extend) throws Exception {
        return BaseParseService.parseMsg(ctx, phoneNumber, smsCenterNum, smsContent, smsTime, extend);
    }

    /**
     * 依据短信接入码,短信中心号码,短信内容分析短信 将短信内容中重要的内容，以键值对的形式
     * 
     * @param ctx
     * @param phoneNumber
     *            短信接入码
     * @param smsCenterNum
     *            短心中心号码
     * @param smsContent
     *            短信内容
     * @param extend
     * @return
     * @throws Throwable
     */
    public static Map<String, Object> parseMsgToMap(Context ctx, String phoneNumber, String smsCenterNum, String smsContent, Map<String, String> extend) throws Exception {
        // if(!SigntureUtil.checkChannelFuncPower(Constant.POWER_TOMAP)) return
        // null;
        if (extend == null) {
            extend = new HashMap<String, String>();
        }
        extend.put("popup_type", "2");
        return  parseMsg(ctx, phoneNumber, smsCenterNum, smsContent, 0l, extend);

    }

    /***
     * 情景汽泡识别导向 提取与短信相关的可互动操作的数据
     * 
     * @param ctx
     * @param phoneNum
     * @param smsCenterNum
     * @param smsContent
     * @param extend
     * @return
     */
    public static String parseMsgToBubble(Context ctx, String phoneNumber, String smsCenterNum, String smsContent, Map<String, String> extend) throws Exception {
        String action = null;
        String uuid = UUIDUtils.uniqId();
        try {
            /*SDK-431 songzhirong 20160530 start*/
            ConversationManager.saveLogIn(uuid,"cn.com.xy.sms.util.ParseManager", "parseMsgToBubble", ctx, phoneNumber,smsCenterNum,smsContent,extend);
            /*SDK-431 songzhirong 20160530 end*/
       
        if (extend == null) {
            extend = new HashMap<String, String>();
        }
        extend.put("popup_type", "2");
        /*SDK-719 zhaojiangwei 20170117 start */
        long smsRecvTime = 0;
        if (extend.containsKey("msgTime")) {
            try{
                smsRecvTime = Long.parseLong(extend.get("msgTime"));
            }
            catch (Exception e) {
                LogManager.e(Constant.TAG, "parseMsgToBubble convert smsRecvTime");
            }
        }
        Map<String, Object> res =  parseMsg(ctx, phoneNumber, smsCenterNum, smsContent, smsRecvTime, extend);
        /*SDK-719 zhaojiangwei 20170117 end */
        if (res != null) {
//            String action = (String) res.get("ADACTION");
            /*SDK-431 songzhirong 20160530 start*/   
            action = BaseParseService.getAdAction(res, extend);
            /*SDK-431 songzhirong 20160530 end*/
            if (action != null) {
                SdkTaskQueue.addTask(new TaskInfo(12, "state", String.valueOf(RecordFunctionUtil.SAMPLE_BUBBLE_STATE)));// 简单气泡标记状态
                return action;
            }/*
              * else{ //无导向服务,则先显示情景名称服务. return
              * XyUtil.getSceneServiceAction(res); }
              */
            }      
        } catch (Throwable e) {
            /*SDK-550 hewengao 20160719 start*/
            LogManager.w(Constant.TAG, "ParseManager parseMsgToBubble: ", e);
            /*SDK-550 hewengao 20160719 end*/
        }finally{
            /*SDK-431 songzhirong 20160530 start*/
            ConversationManager.saveLogOut(uuid,"cn.com.xy.sms.util.ParseManager", "parseMsgToBubble", ctx, phoneNumber,smsCenterNum,smsContent,extend,action);
            /*SDK-431 songzhirong 20160530 end*/
        }
        return null;

    }


    /**
     * 依据号码获取公众号资料信息,包含号码分类信息
     * 
     * @param ctx
     * @param phoneNum
     *            号码
     * @param numType
     *            号码类型 1:接入码 2:电话号码
     * @param simIccid
     * @return
     */
    /*SDK-406 hewengao 20160422 start*/
    public  static String queryPublicInfo(Context ctx, String phoneNum, int numType, String simIccid, Map<String, String> extend) {
        /*SDK-431 songzhirong 20160530 start*/
        String publicInfo = null;
        String uuid = UUIDUtils.uniqId();
        try {
            ConversationManager.saveLogIn(uuid,"cn.com.xy.sms.util.ParseManager", "queryPublicInfo",  ctx,  phoneNum,  numType,  simIccid,  extend);
            /*SDK-431 songzhirong 20160530 end*/           
            if (StringUtils.isPhoneNumber(phoneNum)) {
                return null;
            }
            SdkTaskQueue.addTask(new TaskInfo(12, "state", String.valueOf(RecordFunctionUtil.NUMBER_STATE)));// 记录企业标记状态
            publicInfo = PubInfoService.queryPublicInfo(ctx, phoneNum, numType, simIccid, extend, null);
            /*SDK-768 mobaohua 20170504 start*/
            PublicInfoCacheManager.saveJsonToCache(publicInfo, phoneNum, extend);
            /*SDK-768 mobaohua 20170504 end*/
            return publicInfo;
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "ParseManager queryPublicInfo: ", e);

        }finally{
            /*SDK-431 songzhirong 20160530 start*/
            ConversationManager.saveLogOut(uuid,"cn.com.xy.sms.util.ParseManager", "queryPublicInfo",  ctx,  phoneNum,  numType,  simIccid,  extend,publicInfo);
            /*SDK-431 songzhirong 20160530 end*/

        }
        return "";
        
    }
    /*SDK-406 hewengao 20160422 end*/
    /**
     * 依据号码获取公众号资料信息,包含号码分类信息
     * 
     * @param ctx
     * @param phoneNum
     *            号码
     * @param numType
     *            号码类型 1:接入码 2:电话号码
     * @param simIccid
     * @return
     */
    /*SDK-406 hewengao 20160422 start*/
    public  static String queryPublicInfo(Context ctx, String phoneNum, int numType, String simIccid, Map<String, String> extend, SdkCallBack callBack) {
           
        if (StringUtils.isPhoneNumber(phoneNum)) return null;           
        /*SDK-431 songzhirong 20160530 start*/
        String publicInfo = null;
        String uuid = UUIDUtils.uniqId();
        try {          
            ConversationManager.saveLogIn(uuid,"cn.com.xy.sms.util.ParseManager", "queryPublicInfo",  ctx,  phoneNum,  numType,  simIccid,  extend);
            publicInfo = PubInfoService.queryPublicInfo(ctx, phoneNum, numType, simIccid, extend, callBack);
            /*SDK-768 mobaohua 20170504 start*/
            PublicInfoCacheManager.saveJsonToCache(publicInfo, phoneNum, extend);
            /*SDK-768 mobaohua 20170504 end*/
            return publicInfo;
            /*SDK-431 songzhirong 20160530 end*/
        } catch (Throwable e) {
            // TODO: handle Throwable
            LogManager.e("ParseManager", "queryPublicInfo error: ", e);
        } finally {
            try {
                /*SDK-431 songzhirong 20160530 start*/
                ConversationManager.saveLogOut(uuid,"cn.com.xy.sms.util.ParseManager", "queryPublicInfo",  ctx,  phoneNum,  numType,  simIccid,  extend,publicInfo);
                /*SDK-431 songzhirong 20160530 end*/
                EmergencyQueue.runEmergencyQueue();
                /* RM-1351 huangzhiqiang 20170407 start */
                PubInfoNetService.uploadPubInfoSignNew();
//              PubInfoNetService.uploadPubInfoSign();
                /* RM-1351 huangzhiqiang 20170407 end */
            } catch (Throwable e) {
                LogManager.e("ParseManager", "queryPublicInfo error: ", e);
            }
        }
        return null;

    }
    /*SDK-406 hewengao 20160422 end*/
    /**
     * 依据号码获取公众号资料信息,包含号码分类信息
     * 
     * @param ctx
     * @param phoneNum
     *            号码
     * @param numType
     *            号码类型 1:接入码 2:电话号码
     * @param simIccid
     * @return
     */
    /* SDK-430 huangzhiqiang 20160509 start */
    public static String queryPublicInfoWithId(Context ctx, String phoneNum, int numType, String simIccid, Map<String, String> extend, SdkCallBack callBack) {
    /* SDK-430 huangzhiqiang 20160509 end */
        
        if (StringUtils.isPhoneNumber(phoneNum)) {
            return null;
        }
        /*SDK-431 songzhirong 20160530 start*/
        String publicInfo = null;
        String uuid = UUIDUtils.uniqId();
        try {
            ConversationManager.saveLogIn(uuid,"cn.com.xy.sms.util.ParseManager", "queryPublicInfoWithId",  ctx,  phoneNum,  numType,  simIccid,  extend);
            /*SDK-431 songzhirong 20160530 end*/
            publicInfo = PubInfoService.queryPublicInfoWithId(ctx, phoneNum, numType, simIccid, extend, callBack);
            /*SDK-768 mobaohua 20170504 start*/
            PublicInfoCacheManager.saveJsonToCache(publicInfo, phoneNum, extend);
            /*SDK-768 mobaohua 20170504 end*/
            return publicInfo;
        } catch (Throwable e) {
            // TODO: handle Throwable
            LogManager.e("ParseManager", "queryPublicInfo 2error: ", e);
        } finally {
            try {
                /*SDK-431 songzhirong 20160530 start*/
                ConversationManager.saveLogOut(uuid,"cn.com.xy.sms.util.ParseManager", "queryPublicInfoWithId",  ctx,  phoneNum,  numType,  simIccid,  extend,publicInfo);
                /*SDK-431 songzhirong 20160530 end*/
                EmergencyQueue.runEmergencyQueue();
                /* RM-1351 huangzhiqiang 20170407 start */
                PubInfoNetService.uploadPubInfoSignNew();
//              PubInfoNetService.uploadPubInfoSign();
                /* RM-1351 huangzhiqiang 20170407 end */
            } catch (Throwable e) {
                LogManager.e("ParseManager", "queryPublicInfo error: " , e);
            }

        }
        return null;

    }

    /**
     * 依据号码获取企业动作菜单导向数据
     * 
     * @param ctx
     * @param phoneNum
     *            号码
     * @param numType
     *            号码类型 1:接入码 2:电话号码
     * @param simIccid
     * @param extend
     * @return
     */
    /* SDK-430 huangzhiqiang 20160509 start */
    public static String queryMenuByPhoneNum(Context ctx, String phoneNum, int numType, String simIccid, Map<String, String> extend) {
    /* SDK-430 huangzhiqiang 20160509 end */
      
        if (StringUtils.isPhoneNumber(phoneNum)) {
            return null;
        }
        /*SDK-431 songzhirong 20160530 start*/
        String uuid = UUIDUtils.uniqId();
        String menu = "";
        try {          
            ConversationManager.saveLogIn(uuid,"cn.com.xy.sms.util.ParseManager", "queryMenuByPhoneNum",  ctx,  phoneNum,  numType,  simIccid,  extend);
            /*SDK-431 songzhirong 20160530 end*/
            menu = PubInfoService.queryMenuByPhoneNum(ctx, phoneNum, numType, simIccid, extend, null);
            return menu;
        } catch (Throwable e) {
            // TODO: handle exception
            /* SDK-584 zhaojiangwei 20160906 start */
            DexUtil.saveExceptionLog(e);
            /* SDK-584 zhaojiangwei 20160906 end */
        } finally {
            /*SDK-431 songzhirong 20160530 start*/
            ConversationManager.saveLogOut(uuid,"cn.com.xy.sms.util.ParseManager", "queryMenuByPhoneNum",  ctx,  phoneNum,  numType,  simIccid,  extend,menu);
            /*SDK-431 songzhirong 20160530 end*/
        }
        return null;

    }

    /**
     * 依据号码获取企业动作菜单导向数据
     * 
     * @param ctx
     * @param phoneNum
     *            号码
     * @param numType
     *            号码类型 1:接入码 2:电话号码
     * @param simIccid
     * @param extend
     * @param callBack
     *            回调
     * @return
     */
    /* SDK-430 huangzhiqiang 20160509 start */
    public static String queryMenuByPhoneNum(Context ctx, String phoneNum, int numType, String simIccid, Map<String, String> extend, SdkCallBack callBack) {
    /* SDK-430 huangzhiqiang 20160509 end */
        
        /*SDK-431 songzhirong 20160530 start*/
        String uuid = UUIDUtils.uniqId();
        String menu = "";
        try {
            ConversationManager.saveLogIn(uuid,"cn.com.xy.sms.util.ParseManager", "queryMenuByPhoneNum",  ctx,  phoneNum,  numType,  simIccid,  extend,callBack);
            /*SDK-431 songzhirong 20160530 end*/
            menu = PubInfoService.queryMenuByPhoneNum(ctx, phoneNum, numType, simIccid, extend, callBack);
            return menu;
        } catch (Throwable e) {
            // TODO: handle Throwable
            LogManager.e("ParseManager", "queryMenuByPhoneNum error: ", e);
            /* SDK-584 zhaojiangwei 20160906 start */
            DexUtil.saveExceptionLog(e);
            /* SDK-584 zhaojiangwei 20160906 end */
        } finally {
            try {
                /*SDK-431 songzhirong 20160530 start*/
                ConversationManager.saveLogOut(uuid,"cn.com.xy.sms.util.ParseManager", "queryMenuByPhoneNum",  ctx,  phoneNum,  numType,  simIccid,  extend,callBack,menu);
                /*SDK-431 songzhirong 20160530 end*/       
                EmergencyQueue.runEmergencyQueue();
                /* RM-1351 huangzhiqiang 20170407 start */
                PubInfoNetService.uploadPubInfoSignNew();
//              PubInfoNetService.uploadPubInfoSign();
                /* RM-1351 huangzhiqiang 20170407 end */
            } catch (Throwable e) {
                LogManager.e("ParseManager", "queryPublicInfo error: ", e);
            }
        }
        return null;

    }

    /**
     * 检测发送者号码是否为企业类(通知类)号码
     * 
     * @param ctx
     *            Context
     * @param phoneNumber
     *            需要判断的发送者号码是否为企业类号码
     * @param smsContent
     *            可为null
     * @param extend
     *            可为null
     * @return true :是 通知类; false:不是 通知类
     */
    public static boolean isEnterpriseSms(Context ctx, String phoneNumber, String smsContent, Map<String, String> extend) {
        // 优先用在线算法包中加入这个功能接口.并使用.如果在线识别不了,就用本地.
        if (parseUtilMainJarIsReady()) {
            return DexUtil.isEnterpriseSms(ctx, phoneNumber, smsContent, extend);
        }
        return PopupUtil.isEnterpriseSms(ctx, phoneNumber, smsContent, extend);
    }

    // 是否正在检查更新
    public static boolean isCheckDataForUpdate = false;
    // 检查更新的最后时间
    public static long checkDataForUpdateTime = 0;

    // 1有更新，0没有更新，-1网络不可用,-2正在检查更新
    /**
     * 检查数据是否有更新
     * 
     * @return true有，false没有
     */
    public static void checkDataForUpdate(Map<String, String> extend, SdkCallBack xyCallBack) {
        try {
            if (System.currentTimeMillis() - checkDataForUpdateTime > 1800000) {
                // 当检查更新时间超过了30分钟，直接运行更新
                isCheckDataForUpdate = false;
            }
            if (isCheckDataForUpdate) {
                XyUtil.doXycallBack(xyCallBack, "-2");
                return;
            }
            checkDataForUpdateTime = System.currentTimeMillis();
            isCheckDataForUpdate = true;

            if (!NetUtil.checkAccessNetWork(extend)) {// -1网络不可用
                XyUtil.doXycallBack(xyCallBack, "-1");

            } else {
                boolean isInitData = ParseItemManager.isInitData();
                if (!isInitData) {
                    // 还没初始化完，调用检查更新，返回没有更新
                    XyUtil.doXycallBack(xyCallBack, "0");
                } else {
                    if (JarSubCheckQueue.checkJarUpdate(extend, false, false)) {// 假如jar包有更新，调用xyCallBack
                        XyUtil.doXycallBack(xyCallBack, "1");
                        PubInfoService.checkQueryMenuSql(extend, null);
                    } else {
                        PubInfoService.checkQueryMenuSql(extend, xyCallBack);
                    }
                }

            }

        } catch (Throwable e) {
            // e.printStackTrace();
            LogManager.e(Constant.TAG, "checkDataForUpdate: " + e.getMessage(), e);

        } finally {
            isCheckDataForUpdate = false;
        }

    }

    // 正在更新
    public static boolean isupdateData = false;
    // 更新的时间
    public static long updateDataTime = 0;

    // 2当前数据已经最新，1更新成功，0更新失败，-1网络不可用,-2内部网络错误，-3正在更新
    /**
     * 更新数据
     */
    public static void updateData(final Map<String, String> extend, final SdkCallBack xyCallBack) {
        try {
            if (System.currentTimeMillis() - updateDataTime > 1800000) {
                // 当更新时间超过了30分钟，直接运行更新
                isupdateData = false;
            }
            if (isupdateData) {
                XyUtil.doXycallBack(xyCallBack, "-3");
                return;
            }
            updateDataTime = System.currentTimeMillis();
            isupdateData = true;
            NetUtil.executeRunnable(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.currentThread().setName("xiaoyuan_pool_netutil");
                        android.os.Process.setThreadPriority(SdkTaskQueue.XIAOYUAN_THREA_PRIORITY);
                        if (!NetUtil.checkAccessNetWork(extend)) {// -1网络不可用
                            XyUtil.doXycallBack(xyCallBack, "-1");

                        } else {
                            boolean isInitData = ParseItemManager.isInitData();
                            if (!isInitData) {
                                XyUtil.doXycallBack(xyCallBack, "2");
                            } else {
                                PubInfoService.checkQueryMenuSql(extend, null);
                                MenuInfo menuInfo = MenuInfoManager.queryMenuInfo("menuMain");
                                if (MenuInfoManager.checkMenuUpdate(menuInfo) || JarSubCheckQueue.checkJarUpdate(extend, false, false)) {// 菜单或者是jar包需要更新
                                    if (MenuInfoManager.checkMenuUpdate(menuInfo)) {
                                        MenuInfoManager.downloadMenuInfoNow(menuInfo);
                                    }

                                    if (JarSubCheckQueue.checkDatabaseJarUpdate(extend)) {
                                        // 更新算法包
                                        JarSubCheckQueue.updateJarPackageSyn(extend, xyCallBack);
                                    } else {
                                        menuInfo = MenuInfoManager.queryMenuInfo("menuMain");
                                        if (MenuInfoManager.checkMenuUpdate(menuInfo)) {
                                            // 更新失败

                                            XyUtil.doXycallBack(xyCallBack, "0");

                                        } else { // 更新成功

                                            XyUtil.doXycallBack(xyCallBack, "1");

                                        }

                                    }

                                } else {

                                    XyUtil.doXycallBack(xyCallBack, "2");

                                }

                            }
                        }

                    } catch (Throwable e) {
                        // e.printStackTrace();
                        LogManager.e(Constant.TAG, "updateData: ", e);

                    } finally {
                        isupdateData = false;
                    }
                }
            });

        } catch (Throwable e) {
            // e.printStackTrace();
            LogManager.e(Constant.TAG, "updateData: ", e);

        }

    }

    /**
     * 解析短信并返回解析结果,结果用于短信会话列表创建视图
     * 
     * @param ctx
     *            上下文
     * @param msgId
     *            短消息ID
     * @param phoneNumber
     *            短信接入码,短信发送方号码
     * @param smsCenterNum
     *            短信发送方,短信中心号码
     * @param smsContent
     *            短信内容
     * @param returnCacheType
     *            返回数据的缓存类型 1:返回SDK缓存标识 2:返回SDK识别结果 由开发者保存sdk标识或识别结果.
     * @param extend
     *            Map<String, String>
     * @return Map<String, Object> 包含key CACHE_SDK_MSG_ID 识别结果标识ID
     *         CACHE_SDK_MSG_RESULT:识别结果 value:jsonstring
     * 
     */
    public static Map<String, Object> parseMsgToBubbleCardResult(Context ctx, String msgId, String phoneNumber, String smsCenterNum, String smsContent, long smsReceiveTime, byte returnCacheType, Map<String, String> extend) throws Exception {
      
        // 解析短信
        long start = System.currentTimeMillis();
        /* SDK-402 huangzhiqiang 20160420 start */
        extend = putValueToMap(extend, "msgId", msgId);
        /* SDK-402 huangzhiqiang 20160420 end */
        Map<String, Object> parseValue =  parseMsg(ctx, phoneNumber, smsCenterNum, smsContent, smsReceiveTime, extend);
        long end = System.currentTimeMillis();
//        LogManager.d("duoqu_test", "parseMsg time:" + (end - start));
        if (ParseBubbleManager.getParseStatu(parseValue) == -1) {
            // 识别数据未初始化完毕
            return parseValue;
        }
        if (ParseItemManager.execNqSql) {
//            LogManager.d("duoqu_test", "ParseItemManager.execNqSql: " , ParseItemManager.execNqSql);
            if (parseValue == null) {
                parseValue = new HashMap<String, Object>();
            }
            parseValue.clear();
            parseValue.put("parseStatu", "-2");
            return parseValue;
        }
        // 封装解析结果供汽泡视图显示使用
        Map<String, Object> cardResult = PopupUtil.parseMsgToBubbleCardResult(ctx, msgId, phoneNumber, smsCenterNum, smsContent, smsReceiveTime, returnCacheType, parseValue, false);

        if (cardResult == null) {
//            LogManager.d("duoqu_test", "cardResult: " , cardResult);
        }
        return cardResult;
    }

    public static Map<String, Object> parseMsgToRichAndSimpleBubble(Context ctx, String msgId, String phoneNumber, String smsCenterNum, String smsContent, long smsReceiveTime, byte returnCacheType, Map<String, String> extend) throws Exception {
      
        // 解析短信
        Map<String, Object> parseValue =  BaseParseService.parseMsg(ctx, phoneNumber, smsCenterNum, smsContent, smsReceiveTime, extend);
        if (ParseBubbleManager.getParseStatu(parseValue) == -1) {
            // 识别数据未初始化完毕
            return null;
        }
        // 封装解析结果供汽泡视图显示使用
        Map<String, Object> cardResult = PopupUtil.parseMsgToBubbleCardResult(ctx, msgId, phoneNumber, smsCenterNum, smsContent, smsReceiveTime, returnCacheType, parseValue, false);
//        LogManager.d("MyApplication", "cardResult: " + cardResult);
        return cardResult;
    }

    // private static MemoryCache memoryCache = new MemoryCache();
    private static HashMap<String, Long> publicLoadTime = new HashMap<String, Long>();
//    static ExecutorService publicPool = Executors.newFixedThreadPool(1);
    public static long mins = 1L;

    /*SDK-757 songzhirong 20170407 start*/
    /**
     * 依据图片名称获取图片,图片名称由企业资料
     * 
     * @param ctx
     *            上下文
     * @param logoName
     *            图片名称可为空,当不为空时,可以优化查询速度
     * @param width
     *            图片宽度
     * @param height
     *            图片高度
     * @param logoType
     *            1:方形 固定值
     * @param extend
     *            扩展参数,目前为空
     * @param callBack
     *            可用存在网络访问,如果需要异步查询后得到结果,可以传递此参数, 回调的数据为 Bitmap
     * @return BitmapDrawable
     */
    public static BitmapDrawable findLogoByLogoName(final Context ctx, final String logoName, final int width, final int height, int logoType, Map<String, String> extend, final SdkCallBack callBack){
    	boolean validMd5 = true;
    	if ("OmwdltCwONEPLUS2".equals(KeyManager.channel)) {
    	    validMd5 = false;
        }
        return findLogoByLogoName(ctx, logoName, width, height, logoType, extend, callBack,validMd5);
    }
    /**
     * 依据图片名称获取图片,图片名称由企业资料
     * 
     * @param ctx
     *            上下文
     * @param logoName
     *            图片名称可为空,当不为空时,可以优化查询速度
     * @param width
     *            图片宽度
     * @param height
     *            图片高度
     * @param logoType
     *            1:方形 固定值
     * @param extend
     *            扩展参数,目前为空
     * @param callBack
     *            可用存在网络访问,如果需要异步查询后得到结果,可以传递此参数, 回调的数据为 Bitmap
     * @param validMd5
     *           是否校验md5
     * @return BitmapDrawable
     */
    /*SDK-757 songzhirong 20170407 end*/
    /*SDK-757 songzhirong 20170407 start*/
    /* SDK-430 huangzhiqiang 20160509 start */
    public static BitmapDrawable findLogoByLogoName(final Context ctx, final String logoName, final int width, final int height, int logoType, Map<String, String> extend, final SdkCallBack callBack,final boolean validMd5) {
    /* SDK-430 huangzhiqiang 20160509 end */
    /*SDK-757 songzhirong 20170407 end*/
        BitmapDrawable dr = null;
        /*SDK-431 songzhirong 20160530 start*/
        String uuid = UUIDUtils.uniqId();
        try {
            ConversationManager.saveLogIn(uuid,"cn.com.xy.sms.util.ParseManager", "findLogoByLogoName", ctx, logoName,width,height,logoType,extend,callBack);
            /*SDK-431 songzhirong 20160530 end*/
            final String logoDir = Constant.getPath("duoqu_publiclogo");
            final String logoPath = logoDir + logoName;

            File file = new File(logoPath);

            if (file.exists()) {
                // 说明文件存在
                // BitmapFactory.deco
                dr = ViewUtil.createBitmapByPath2(ctx, file, width, height);
                if (dr != null) {
                    XyUtil.doXycallBackResult(callBack, dr);
                    return dr;
                } else {
                    publicLoadTime.put(logoPath, System.currentTimeMillis());
                    XyUtil.doXycallBackResult(callBack, null);
                    return null;
                }
            } else {

                Long time = publicLoadTime.get(logoPath);
                if (time != null && (System.currentTimeMillis() < (time + DexUtil.getUpdateCycleByType(OnlineUpdateCycleConfigInterface.TYPE_REDOWNLOAD_LOGO_INTERVAL, 60 * mins * 1000L)))) {
                    XyUtil.doXycallBackResult(callBack, null);
                    return null;
                }

                final String bizport = NetUtil.BIZPORT_DOWN_URL + logoName;
                boolean syn = false;
                if (extend != null && !extend.isEmpty()) {
                    syn = "true".equals(extend.get("syn"));
                }
                if (!syn) {
                     /*SDK-616 hewengao 20160912 start*/
//                    SmartSmsThreadPoolManager.publicPool2
//                    SmartSmsThreadPoolManager.publicPool;
                    SmartSmsThreadPoolManager.getLogoService().execute(new Runnable() {
                     /*SDK-616 hewengao 20160912 end*/
                        @Override
                        public void run() {
                            try {
                                /*SDK-616 hewengao 20160912 start*/
                                SmartSmsThreadPoolManager.setThreadNameAndPriority(SmartSmsThreadPoolManager.TNAME_PUBLICPOOL,
                                        Process.THREAD_PRIORITY_BACKGROUND);
                                /*SDK-616 hewengao 20160912 end*/
                                /*SDK-757 songzhirong 20170407 start*/
                                downAndCreateDrawable(ctx, bizport, logoDir, logoName, logoPath, width, height, callBack,validMd5);
                                /*SDK-757 songzhirong 20170407 end*/
                            } catch (Throwable e) {
                                LogManager.e(Constant.TAG, e.getMessage(), e);
                            }

                        }
                    });
                } else {
                    /*SDK-757 songzhirong 20170407 start*/
                    dr = downAndCreateDrawable(ctx, bizport, logoDir, logoName, logoPath, width, height, callBack,validMd5);
                    /*SDK-757 songzhirong 20170407 end*/
                }

            }
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "ParseManager findLogoByLogoName: ", e);

        } finally {
            /*SDK-431 songzhirong 20160530 start*/
            ConversationManager.saveLogOut(uuid,"cn.com.xy.sms.util.ParseManager", "findLogoByLogoName", ctx, logoName,width,height,logoType,extend,callBack,dr);
            /*SDK-431 songzhirong 20160530 end*/
            Long time = publicLoadTime.get("runResourseQueue");
            if (time == null || (System.currentTimeMillis() > (time + DexUtil.getUpdateCycleByType(OnlineUpdateCycleConfigInterface.TYPE_RUN_RESOURSE_QUEUE_CYCLE, 3600000L)))) {
                SdkTaskQueue.addTask(new TaskInfo(7));
                publicLoadTime.put("runResourseQueue", System.currentTimeMillis());
            }
        }
        SdkTaskQueue.addTask(new TaskInfo(12, "state", String.valueOf(RecordFunctionUtil.COMPANY_LOGO_STATE)));// 设置企业logo状态标记

        return dr;
    }
    /*SDK-757 songzhirong 20170407 start*/
    private static BitmapDrawable downAndCreateDrawable(Context ctx, String bizportUrl, String logoDir, String logoName, String logoPath, int width, int height, final SdkCallBack callBack,boolean validMd5) {
    /*SDK-757 songzhirong 20170407 end*/
    	BitmapDrawable dr = null;
        try {
            // 走cdn下载logo

            if (!NetUtil.checkAccessNetWork(2)) {
                if (callBack != null) {
                    callBack.execute(null);
                }
                return null;
            }
            publicLoadTime.put(logoPath, System.currentTimeMillis());
            /*SDK-470 hewengao 20160630 start*/
            int result = FileUtils.downFileAndVerifyWithMd5(bizportUrl, logoDir, logoName,validMd5);
            /*SDK-470 hewengao 20160630 end*/
            if (result == 0) {// 下载成功
                publicLoadTime.remove(logoPath);
                dr = ViewUtil.createBitmapByPath2(ctx, logoPath, width, height);
                if (callBack != null) {
                    callBack.execute(dr);
                }
                if (dr != null) {
                    publicLoadTime.remove(logoPath);
                    // memoryCache.put(logoPath, dr);
                }
            } else {// 下载失败
                if (callBack != null) {
                    callBack.execute(null);
                }
            }
        } catch (Throwable e) {
            // TODO: handle Throwable
        }
        return dr;
    }

    /**
     * 根据时间获取算包版本号插入数据库
     * 
     * @throws Throwable
     */
    private static void addViewVersion(String time, String version) throws Throwable {
        String versionStr = version + "_" + time;
        SysParamEntityManager.insertOrUpdateKeyValue(Constant.getContext(), "bubbleViewVersion", versionStr, null);
        SysParamEntityManager.cacheMap.put("bubbleViewVersion", versionStr);
    }

    /**
     * 依据航班号和航班时间，获取航班到达时间
     * 
     * @param flightNum
     *            航班号
     * @param flightDate
     *            航班时间
     * @param extend
     *            扩展参数
     * @param callBack
     *            无数据或异常时返回参数为null，正常情况返回参数： index0(String):短信ID
     *            index1(JSONObject):航班信息Json对象 例: {"FlightCompany":"上海航空有限公司",
     *            "FlightDeptimePlanDate":"2014-12-01 18:30:00",
     *            "FlightArrtimePlanDate":"2014-12-01 21:05:00",
     *            "FlightHTerminal":"T2","FlightDep":"上海",
     *            "FlightArr":"广州","FlightQueryTime":1433300561019,
     *            "FlightDepAirport":"上海虹桥国际", "FlightArrAirport":"广州白云国际"}
     */
    public static void queryFlightData(final String id, String flightNum, String flightDate, Map<String, Object> extend, final SdkCallBack xyCallBack) {
        TravelService.queryFlightData(id, flightNum, flightDate, extend, xyCallBack);
    }

  


    /**
     * 判断车次途经站信息是否符合要求
     * 
     * @param stationList
     *            车次途经站信息集合
     * @param from
     *            出发地
     * @param to
     *            目的地
     * @param isOnlineData
     *            (已弃用)是否联网查询的数据
     * @return true:符合要求 false:不符合要求
     */
    public static boolean checkStationList(String stationList, String from, String to, boolean isOnlineData) {
       return TravelService.checkStationList(stationList, from, to, isOnlineData);
    }

    /**
     * 设置默认服务开关,H5相关
     * 
     * @param ctx
     * @param flag
     *            开：1 关：0
     * @return 失败 -1 异常 -2 成功 0
     */
    public static long setDefServiceSwitch(Context ctx, String flag) {
        long result = -1;
        try {

            SysParamEntityManager.insertOrUpdateKeyValue(ctx, "defService", flag, null);
            result = 0;
        } catch (Throwable e) {
            // TODO Auto-generated catch block
            // e.printStackTrace();
            result = -2;
        }
        return result;
    }

    /**
     * 查询默认服务开关状态
     * 
     * @param ctx
     * @return 从未设置： null 开：1 关：其他
     */
    public static String queryDefService(Context ctx) {

        return SysParamEntityManager.queryValueParamKey(ctx, "defService");
    }

   

    public static boolean isInitData() {       
        return ParseItemManager.isInitData();
    }

    /***
     * 删除缓存数据，依据情景ID 及 最后解析时间。
     * 
     * @param sceneId
     * @param endParseTime
     */
    public static void deleteMatchCache(String sceneId, long endParseTime) {
        try {
            MatchCacheManager.deleteMatchCache(sceneId, endParseTime);
        } catch (Throwable e) {
            // e.printStackTrace();
            LogManager.e(Constant.TAG, "deleteMatchCache: ", e);

        }
    }

    public static void deleteMatchCache(String sceneId, String clName, long endParseTime) {
        try {
            MatchCacheManager.deleteMatchCache(sceneId, clName, endParseTime);
        } catch (Throwable e) {
            // e.printStackTrace();
            LogManager.e(Constant.TAG, "deleteMatchCache: ", e);

        }
    }
    
    
    /*SDK-586 zhaojiangwei 20160812 start */
    public static void clearRecognisedSdkCache(String phone){
    	if (StringUtils.isNull(phone)) {
    		SdkCache.clearRecogniseSdkCache();	
		}
    	else{
    		SdkCache.clearRecogniseSdkCache(phone);	
    	}
    }
    /*SDK-586 zhaojiangwei 20160812 end */

    /**
     * 根据号码获所属运营商编号
     * 
     * @param num
     * @return 1:联通 2:移动 3:电信 -1:未知
     */
    public static int getOperatorByNum(String num) {
        if (StringUtils.isNull(num))
            return -1;
        num = StringUtils.getPhoneNumberNo86(num);
        return IccidLocationUtil.getOperatorByNum(num);
    }

    /**
     * 开启增加开关
     * 
     * @param callBack
     */
    public static void setSmartEnhance(boolean isOpen) {
        try {
            SysParamEntityManager.insertOrUpdateKeyValue(Constant.getContext(), Constant.SMARTSMS_ENHANCE, String.valueOf(isOpen), null);
            SysParamEntityManager.cacheMap.put(Constant.SMARTSMS_ENHANCE, isOpen);
        } catch (Throwable e) {
            // e.printStackTrace();
            LogManager.e(Constant.TAG, "setSmartEnhance: ", e);

        }
    }

    /**
     * 加载归属地
     * 
     * @param iccid
     *            非必须
     * @param num
     *            非必须
     * @param simIndex
     *            非必须
     * @param newThread
     *            true 新开线程,false 不需要新开线程。
     */
    public static void loadLocation(String iccid, int simIndex, String num, boolean newThread) {
        /* SDK-485 huangzhiqiang 20160622 start */
        IccidLocationUtil.queryIccid(null, iccid, num, newThread, true);
        /* SDK-485 huangzhiqiang 20160622 end */
    }

    /*SDK-768 mobaohua 20170504 start*/
    public static HashMap<String, JSONObject> loadAllPubInfo(Set<String> pubIds) {
        return loadAllPubInfo(pubIds, false);
    }
    
    public static HashMap<String, JSONObject> loadAllPubInfo(Set<String> pubIds, boolean addCatch) {
        HashMap<String, JSONObject> result = PubInfoManager.loadAllPubInfo(pubIds);
        if (addCatch&&result!=null&&!result.isEmpty()) {
            PublicInfoCacheManager.putAllTopublicInfoData(result);
        }
        return result;
    }
    /*SDK-768 mobaohua 20170504 end*/

    /*SDK-449 zhaojiangwei 20160524 start*/
    /*SDK-768 mobaohua 20170504 start*/
    public static HashMap<String, String[]> loadAllPubNum(Set<String> phoneNumbers) {
        return loadAllPubNum(phoneNumbers, false);
    }
    
    public static HashMap<String, String[]> loadAllPubNum(Set<String> phoneNumbers, boolean addCatch) {
        HashMap<String, String[]> numResult = PubInfoManager.loadAllPubNum(phoneNumbers);
        if (addCatch && numResult != null && !numResult.isEmpty()) {
            PublicInfoCacheManager.putAllToPhonePublicIdData(numResult);
        }
        return numResult;
    }
    /*SDK-768 mobaohua 20170504 end*/
    /*SDK-449 zhaojiangwei 20160524 end*/

    /***
     * 立即更新jar包
     */
    public static void updateNow() {
        JarSubCheckQueue.checkJarsUpdate(true, false);
    }

    /**
     * 根据公众号获取公众号对应的运营商编号(1:移动 2:联通 3:电信 -2:未知)
     * 
     * @param pubId
     * @return
     */
    public static int getOperatorNumByPubNum(String pubNum) {
        return PubInfoManager.getOperatorNumByPubNum(pubNum);
    }

    /**
     * 是否需要更新算法包
     * 
     * @return
     */
    public static boolean needUpdateJar() {
        return JarSubInfoManager.needUpdateJar();
    }

    /**
     * 获取SDK版本号
     * 
     * @return 版本号 versionNum
     */
    public static String getSdkVersion() {
        return NetUtil.APPVERSION;
    }

    /* MEIZU-935 huangzhiqiang 20160713 start */
    public static String getUIVersion() {
        return DexUtil.getUIVersion();
    }
    /* MEIZU-935 huangzhiqiang 20160713 end */

    public static void setLogSdkDoAction(LogSdkDoAction logSdkDoAction) {
        DuoquUtils.logSdkDoAction = logSdkDoAction;
    }

    public static int getParseVersion(Context ctx, Map extend) {
        int defaultVerion = 0;
        try {
            String version = SdkParamUtil.getParamValue(ctx, "PARSE_VERSION");
            if (!StringUtils.isNull(version)) {
                return Integer.parseInt(version);
            }
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "getParseVersion", e);
        }
        return defaultVerion;
    }

    /**
     * 获取所有SIM卡指定运营商客服公众号的查话费及查流量的动作数据
     * 
     * @param context
     * @param pubNum
     *            运营商客服公众号(10086/10010/10000)
     * @param callBack
     *            index0(int):(0:查询失败 1:查询成功)
     *            index1(String)：查询失败时为失败说明，查询成功时为ICCID
     *            index2(String):菜单JSONArray字符串数据(查询成功才存在index2)
     */
    public static void queryAllSimCardTrafficAndChargeActionData(Context context, String pubNum, final SdkCallBack callBack) {
        try {
            HashMap<String, String[]> iccidMap = IccidLocationUtil.getIccidAreaCodeMap();
            if (iccidMap == null) {
                callBack.execute(0, "iccidMap is null");
                return;
            }
            Set<Entry<String, String[]>> setEntery = iccidMap.entrySet();
            for (Entry<String, String[]> entry : setEntery) {
                final String iccid = entry.getKey();
                ParseManager.queryMenuByPhoneNum(context, pubNum, 1, iccid, null, new SdkCallBack() {
                    @Override
                    public void execute(Object... menuJsonDataArr) {
                        try {
                            if (menuJsonDataArr == null || menuJsonDataArr.length == 0 || menuJsonDataArr[0] == null || !menuJsonDataArr[0].toString().contains("action_data")) {
                                callBack.execute(0, "menu json data error");
                                return;
                            }
                            callBack.execute(1, iccid, PubInfoManager.findQueryTrafficAndChargeActionData((String) menuJsonDataArr[0]));
                        } catch (Throwable t) {
                            // t.printStackTrace();
                            LogManager.e(Constant.TAG, "queryAllSimCardTrafficAndChargeActionData: ", t);

                            callBack.execute(0, "error:" + t.getMessage());
                        }
                    }
                });
            }
        } catch (Throwable t) {
            // t.printStackTrace();
            LogManager.e(Constant.TAG, "queryAllSimCardTrafficAndChargeActionData: ", t);

            callBack.execute(0, "error:" + t.getMessage());
        }
    }

    /**
     * 添加查流量及查话费的菜单数据到全国菜单
     * 
     * @param menuDataCN
     *            全国菜单数据
     * @param iccid2MenuActionDataMap
     *            所有SIM卡的查流量、查话费菜单数据
     * @return
     */
    public static String addQueryTrafficAndChargeToMenuData(String menuDataCN, Map<String, String> iccid2MenuActionDataMap) {
        return PubInfoManager.addQueryTrafficAndChargeToMenuData(menuDataCN, iccid2MenuActionDataMap);
    }

    /***
     * 获取算法版本
     * @return
     */
    public static String getAlgorithmVerion() {
        String org = "";
        try {
            org = JarSubInfoManager.getJarMaxPver();
            if (StringUtils.isNull(org))
                return "";
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            Date date = df.parse(org);
            df = new SimpleDateFormat("yyyyMMddHH");
            org = df.format(date);

        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "getAlgorithmVerion", e);
        }
        return org;
    }

    /* SDK-566 huangzhiqiang 20160729 start */
    /**
     * 将渠道号添加到扩展参数，如果extend参数为null时注意在调用方法处将返回值赋值给extend变量，即extend = putChannelToExtend(extend);
     * 
     * @param extend
     * @return
     */
    private static Map putChannelToExtend(Map extend) {
        if (extend == null) {
            extend = new HashMap();
        }
        try {
            KeyManager.initAppKey();
            extend.put(Constant.CHANNEL, XyHttpRunnable.appKey);
        } catch (Throwable e) {
            LogManager.e(Constant.TAG, "ParseManager putChannelToExtend error", e);
        }
        return extend;
    }
    /* SDK-566 huangzhiqiang 20160729 end */

	/* SDK-617 zhaojiangwei 20160912 end */
    /**
     * 气泡数据缓存入库
     * 
     * @throws JSONException
     */
    public static void updateMatchCacheManager(BusinessSmsMessage smsMessage) {
        if (smsMessage == null) {
            return;
        }
        try {
            /* SDK-597 songzhirong 20160824 start*/
            JSONObject json = new JSONObject(smsMessage.bubbleJsonObj.toString());
            updateMatchCacheManager((String) smsMessage.getValue("phoneNum"), smsMessage.getTitleNo(), String.valueOf(smsMessage.getSmsId()), json, smsMessage.getMessageBody());
        } catch (Throwable e) {
            /* SDK-597 songzhirong 20160824 end*/
            // ex.printStackTrace();
            LogManager.e(Constant.TAG, "updateMatchCacheManager: ", e);

        }
    }

    /**
     * 丰富气泡数据缓存入库
     * 
     * @throws JSONException
     */
    public static void updateMatchCacheManager(String phoneNumber, String titleNo, String msgId,
            JSONObject bubbleJsonObj, String messageBody) throws JSONException {
        MatchCacheManager.updateMatchCacheManager(phoneNumber, titleNo, msgId, bubbleJsonObj, messageBody);
    }
    
    /* SDK-695 huangzhiqiang 20161207 begin */
    /**
     * 丰富气泡、简单气泡数据缓存入库
     * 
     * @throws JSONException
     */
    public static void updateMatchCacheManager(String phoneNumber, String titleNo, String msgId,
            JSONObject bubbleResult, JSONArray sessionReuslt, String messageBody) throws JSONException {
        MatchCacheManager
                .updateMatchCacheManager(phoneNumber, titleNo, msgId, bubbleResult, sessionReuslt, messageBody);
    }
    /* SDK-695 huangzhiqiang 20161207 end */

    /**
     * 根据车次查询本地数据库车次途经站信息，如数据库无相关车次信息则使用联网查询接口
     * 
     * @param id
     *            短信ID
     * @param trainNum
     *            车次号
     * @param from
     *            出发地
     * @param to
     *            目的地
     * @param extend
     *            扩展参数
     * @param callBack
     *            回调函数 无数据或异常时返回参数为null，正常情况返回参数： index0(String):短信ID
     *            index1(JSONObject):车次信息Json对象
     *            例:{"station_list":"[{\"name\":\"重庆北\",\"spt\":\"07:48\", \
     *            "stt\":\"07:48\"},{\"name\":\"广安\",\"spt\":\"09:13\",\"stt\":\"09:20\"}]"
     *            } 其中name为站点名，spt为到站时间，stt为出站时间 index2(String):车次号
     *            index3(String):出发地 index4(String):目的地
     *            index5(boolean):true=联网接口 false=本地接口
     */
    public static void queryTrainInfo(final String id, final String trainNum, final String from, final String to, final Map<String, Object> extend, final SdkCallBack callBack) {
        TravelService.queryTrainInfo(id, trainNum, from, to, extend, callBack);
    }   

    public static Map<String, String> putValueToMap(Map<String, String> extendMap, String key, String value) {
        if (extendMap == null) {
            extendMap = new HashMap<String, String>();
        }
        extendMap.put(key, value);
        return extendMap;
    }
    /*SDK-407 hewengao 20160425 start*/
    /***
     * 判断号码，是否固定电话
     * @param ctx
     * @param phoneNumber   需要判断的号码 
     * @param extend   扩展参数可为空
     * @return
     */
    public static boolean isFixedPhone(Context ctx, String phoneNumber, Map<String, String> extend){
        return PopupUtil.isFixedPhone(phoneNumber);
    }
    /*SDK-407 hewengao 20160425 end*/
    
    /*SDK-425 lilong 20160510 start*/
    public static boolean geOnOffByType(int type){
        return DexUtil.geOnOffByType(type);
    }
    /*SDK-451/yangzhi/2016.05.23---start---*/
    public static JSONArray getConfigByType(int type, String uiversion, Integer suportMenuId){
        return DexUtil.getConfigByType(type, uiversion, suportMenuId);
    }
    /*SDK-451/yangzhi/2016.05.23---end---*/
    
    /*SDK-425 lilong 20160510 end*/
    

    /**
     * 依据航班号和航班时间，获取航班到达时间
     * 
     * @param flightNum
     *            航班号
     * @param flightDate
     *            航班时间
     * @param extend
     *            扩展参数
     * @param callBack
     *            无数据或异常时返回参数为null，正常情况返回参数： index0(String):短信ID
     *            index1(JSONObject):航班信息Json对象 例: {"FlightCompany":"上海航空有限公司",
     *            "FlightDeptimePlanDate":"2014-12-01 18:30:00",
     *            "FlightArrtimePlanDate":"2014-12-01 21:05:00",
     *            "FlightHTerminal":"T2","FlightDep":"上海",
     *            "FlightArr":"广州","FlightQueryTime":1433300561019,
     *            "FlightDepAirport":"上海虹桥国际", "FlightArrAirport":"广州白云国际"}
     */
    public static void queryFlightData( String flightNum, String flightDate, Map<String, Object> extend, final SdkCallBack xyCallBack) {
        TravelService.queryFlightData(flightNum, flightDate, extend, xyCallBack);
    }
    
    /*SMARTISAN-129 songzhirong 20160819 start*/ 
    public static void reInitAlgorithm(final Context context,final SdkCallBack xyCallBack){
        InitUtil.reInitAlgorithm(context, xyCallBack);
    }
    /*SMARTISAN-129 songzhirong 20160819 end*/


	/*SDK-683 zhaojiangwei 20161121 start */
	public static void cleanToken(Context context){
    	   try {
    		Constant.initContext(context);
			DBManager.delete(SysParamEntityManager.TABLE_NAME, SysParamEntityManager.PKEY + " = ?", new String[] {"NEWHTTPTOKEN"});
			DBManager.delete(SysParamEntityManager.TABLE_NAME, SysParamEntityManager.PKEY + " = ?", new String[] {"HTTPTOKEN"});
   			DBManager.delete(SysParamEntityManager.TABLE_NAME, SysParamEntityManager.PKEY + " = ?", new String[] {"AESKEY"});
		} catch (Throwable e) {
			// TODO Auto-generated catch block
			LogManager.e("xiaoyuan", "cleanToken ",e);
		}
	}
	/*SDK-683 zhaojiangwei 20161121 end */
   
    
    /*MEIZU-2295 songzhirong 20170330 start*/
    public static Map<String, Object>  parseMessage(Context ctx, String phoneNumber,String smsContent,String smsCenterNum,long smsTime,Map<String, String> extend) throws Exception{
    	return  BaseParseService.parseMessage(ctx, phoneNumber, smsContent,smsCenterNum,smsTime, extend);
    }
    /*MEIZU-2295 songzhirong 20170330 end*/
    
    /*SDK-768 mobaohua 20170504 start*/
    public static JSONObject getPublicInfoById(String pubId){
        return PublicInfoCacheManager.getPublicInfoById(pubId);
    }
    
    public static JSONObject getPublicInfoByPhoneIncache(String phone) {
        return PublicInfoCacheManager.getPublicInfoByPhoneIncache(phone);
    }
    /*SDK-768 mobaohua 20170504 end*/

}